package NetWork;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServer {

    private ServerSocket serverSocket = null;//为服务器提供的网卡

    public TcpServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);  //这个socket就认为，你一旦
    }

    public void start() throws IOException {
        System.out.println("服务器启动->");
        ExecutorService executorService = Executors.newCachedThreadPool();
        while (true) {
            Socket clientSocket = serverSocket.accept(); //这里要通过客户端的serverSocket接收,先进行连接，因为为TCP是面向连接的
          /*  Thread thread = new Thread(()->{
                System.out.printf("为IP :%s  Port :%d 的客户服务", clientSocket.getInetAddress(), clientSocket.getPort());
                System.out.println();
                try {
                    process(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
            thread.start();

           */
            System.out.printf("为IP :%s  Port :%d 的客户服务", clientSocket.getInetAddress(), clientSocket.getPort());
            System.out.println();
            executorService.submit(()->{
                try {
                    process(clientSocket);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });

        }

    }
    public void process(Socket clientSocket) throws IOException {
        try (InputStream inputStream = clientSocket.getInputStream();  //客户端发过来的一个socket数据报
             OutputStream outputStream = clientSocket.getOutputStream();) {
       while(true) {  //这个while跳出其他的客户端才能与服务器连接
               Scanner sc = new Scanner(inputStream); //读取客户端发过来的文件
               if (!sc.hasNext()) {
                   System.out.println("客户端无请求了下线");
                   break;  //
               }
               String request = sc.next();
               String repose = getRepose(request);
           PrintWriter printWriter = new PrintWriter(outputStream);
           printWriter.println(repose);
           printWriter.flush();
           }
       } catch (IOException e){

        }

    }

    public String getRepose(String repose){
        return repose;
    }
    public static void main(String[] args) throws IOException {
       TcpServer tcpServer =new TcpServer(9090);
       tcpServer.start();
    }
}
